package com.whg.shiro.config;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @Author whg
 * @create 2022/10/12 16:38
 * @description：自定义Filter
 */
public class CustomRolesOrAuthorizationFilter extends AuthorizationFilter {

    public CustomRolesOrAuthorizationFilter(){

    }
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        Subject subject = this.getSubject(servletRequest,servletResponse);
        //获取访问当前路径所需要的角色集合
        String[] rolesArray = (String[])((String[])o);
        if(rolesArray != null && rolesArray.length > 0){
            for (String role : rolesArray){
                //当前subject拥有角色集合中的任意一个角色，则有权访问
                if(subject.hasRole(role)){
                    return true;
                }
            }
            return false;
        }
        //没有角色限制，可以直接访问
        return true;
    }
}
